<?php
namespace Admin\Controller;

use Think\Controller;
use Org\Util\Image;
use Org\Util\Rbac;
use Think\Crypt;

/**
 * 公共类
 *
 * @author ryan
 *        
 */
class PublicController extends Controller
{

    public function index()
    {
        header("Location:" . __MODULE__ . "/Public/login");
    }

    public function login()
    {
        if (! isset($_SESSION[C('USER_AUTH_KEY')])) {
            $this->display();
        } else {
            header("Location:" . __MODULE__ . "/Index");
        }
    }

    public function checkLogin()
    {
        $account = I('username');
        $password = I('password');
        $vercode = I('vercode');
        if (empty($account)) {
            $this->error('用户名不能为空');
        }
        if (empty($password)) {
            $this->error('密码不能为空');
        }
        if (empty($vercode)) {
            $this->error('验证码不能为空');
        }
        if ($_SESSION['verify'] != md5($vercode)) {
            $this->error('验证码错误！');
        }
        // 生成认证条件
        $map = array();
        // 支持使用绑定帐号登录
        $map['username'] = $account;
        $map["status"] = 0;
        $user = Rbac::authenticate($map);
        if (empty($user)) {
            $this->error('用户不存在或禁用');
        } else {
            if ($user['password'] == md5($password)) {
                $token = md5($user['id'] . TIMESTAMP);
                $data = array();
                $data['user_id'] = $user['id'];
                $data['token'] = $token;
                $data['last_login_time'] = TIMESTAMP;
                $data['last_login_ip'] = get_client_ip();
                $data['add_time'] = TIMESTAMP;
                $status = D('UserToken')->add($data);
                if ($status === false) {
                    $this->error('服务器异常，请重试');
                }
                $_SESSION['user_info'] = Crypt::encrypt(json_encode($user), C('USER_AUTH_KEY'));
                $_SESSION[C('USER_AUTH_KEY')] = $user['id'];
                $_SESSION['lastLoginTime'] = TIMESTAMP;
                if ($user['is_admin'] == 1) {
                    $_SESSION[C('ADMIN_AUTH_KEY')] = true; // 超级管理员
                }
                D('User')->where(array(
                    'id' => $user['id']
                ))->save(array(
                    'last_login_time' => TIMESTAMP,
                    'last_login_ip' => get_client_ip()
                ));
                Rbac::saveAccessList();
                $this->ajaxReturn(array(
                    'status' => 1,
                    'info' => '登录成功',
                    'token' => $token,
                    'url' => U('Index/index')
                ));
            } else {
                $this->error('用户名或密码错误');
            }
        }
    }

    public function logout()
    {
        $token = I('token');
        if (empty($token)) {
            $this->error('无权限操作');
        }
        $user_token = D('UserToken')->where(array(
            'token'
        ))->find();
        if ($user_token['status'] == 1) {
            unset($_SESSION[C('USER_AUTH_KEY')]);
            unset($_SESSION);
            session_destroy();
            $this->error('已经登出', __CONTROLLER__ . '/login/');
        } else if (isset($_SESSION[C('USER_AUTH_KEY')])) {
            unset($_SESSION[C('USER_AUTH_KEY')]);
            unset($_SESSION);
            session_destroy();
            D('UserToken')->where(array(
                'id' => $user_token['id']
            ))->save(array(
                'status' => 1
            ));
            $this->success('登出成功！', __CONTROLLER__ . '/login/');
        } else {
            unset($_SESSION[C('USER_AUTH_KEY')]);
            unset($_SESSION);
            session_destroy();
            $this->error('已经登出！', __CONTROLLER__ . '/login/');
        }
    }

    /**
     * 验证码
     */
    public function verify()
    {
        $type = isset($_GET['type']) ? $_GET['type'] : 'gif';
        Image::buildImageVerify(4, 1, $type, 60, 24);
    }

    /**
     * 顶部菜单
     */
    public function menus()
    {
        $token = I('token');
        if (empty($token)) {
            $this->ajaxReturn(array());
        }
        $user_token = D('UserToken')->where(array(
            'token' => $token,
            'status' => 0
        ))->find();
        if (empty($user_token)) {
            $this->ajaxReturn(array());
        }
        if (! $_SESSION[C('ADMIN_AUTH_KEY')]) {
            $menus = D('Menu')->menuList($_SESSION[C('USER_AUTH_KEY')]);
        } else {
            $menus = D('Menu')->where("pid = 0 AND status = 0")
                ->field('id,menu_name as title,icon')
                ->order('sort_order asc')
                ->select();
        }
        $this->ajaxReturn($menus);
    }

    public function navMenus()
    {
        $token = I('token');
        $list = array();
        if (empty($token)) {
            $this->ajaxReturn($list);
        }
        $user_token = D('UserToken')->where(array(
            'token' => $token,
            'status' => 0
        ))->find();
        if (empty($user_token)) {
            $this->ajaxReturn($list);
        } else {
            $pid = I('pid');
            $menus = D('Menu')->nodes(array(
                'pid' => $pid,
                'status' => 0
            ), 2);
            $list = $menus;
        }
        $this->ajaxReturn($list);
    }

    public function regionsToOption()
    {
        $pid = I('pid');
        $regions = D('Regions')->where(array(
            'pid' => $pid
        ))->select();
        $html = '';
        foreach ($regions as $region) {
            $option = "<option value='{$region['id']}'>{$region['name']}</option>";
            $html .= $option;
        }
        $this->ajaxReturn(array(
            'html' => $html
        ));
    }
}

